import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/get_book")
public class GetBook extends HttpServlet {
    private static final String DB_URL = "jdbc:mysql://localhost:3306/linux_exam";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "1qaz@WSX#EDC";

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        resp.setHeader("Access-Control-Allow-Origin","*");
        resp.setHeader("Access-Control-Allow-Methods","*");
        resp.setHeader("Access-Control-Allow-Headers","*");

        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();

        String number = req.getParameter("number");

        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             PreparedStatement stmt = conn.prepareStatement(
                     "SELECT * FROM t_book WHERE number = ?")) {

            stmt.setString(1, number);
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                out.printf("{\"number\":\"%s\",\"name\":\"%s\",\"author\":\"%s\"}",
                        rs.getString("number"),
                        rs.getString("name"),
                        rs.getString("author"));
            } else {
                out.print("{\"status\":\"error\",\"message\":\"Book not found\"}");
            }
        } catch (SQLException e) {
            out.printf("{\"status\":\"error\",\"message\":\"%s\"}", e.getMessage());
        }
        out.close();
    }
}